package com.quick.proxy.core.handler;

import cn.hutool.json.JSONUtil;
import com.quick.proxy.core.ChannelAttribute;
import com.quick.proxy.core.ProxyMessage;
import com.quick.proxy.core.utils.ProtocolUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Optional;


/**
 * Description: 接收数据时解码
 * Author: 吃素不吃肉
 * Date: 2023/7/4
 *
 * @author 吃素不吃肉
 */
@Slf4j
public class ProtocolDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
        byte[] decodeBytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(decodeBytes);
        if (ProtocolUtils.checkBcc(decodeBytes)) {
            String accessKey = Optional.ofNullable(channelHandlerContext.channel().attr(ChannelAttribute.ACCESS_KEY_PROXY_CHANNEL).get()).orElse("auth");
            ProxyMessage proxyMessage = ProtocolUtils.getProxyMessage(decodeBytes);
            log.debug("[{}][{}]<-{}", accessKey, proxyMessage.getCmdType(), JSONUtil.toJsonStr(proxyMessage));
            list.add(proxyMessage);
        }
    }
}
